package com.zjdiepu.www.manage.api.dh;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.RefundStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.ExcelTitleRowConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.ExcelUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.config.FileProperty;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.dh.IDhOverdueListHistoryService;
import com.zjdiepu.www.ibiz.dh.IDhOverdueListService;
import com.zjdiepu.www.ibiz.dh.IOverdueBatchService;
import com.zjdiepu.www.ibiz.dh.IOverdueService;
import com.zjdiepu.www.ibiz.dz.IDzLoanMiddleBankService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessExtrasService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.model.dh.dto.DhOverdue;
import com.zjdiepu.www.model.dh.dto.DhOverdueBatch;
import com.zjdiepu.www.model.dh.dto.DhOverdueList;
import com.zjdiepu.www.model.dh.ext.DhOverdueExt;
import com.zjdiepu.www.model.dh.vo.DhOverdueVo;
import com.zjdiepu.www.model.dz.dto.DzLoanMiddleBank;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessExtras;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.ext.YwBusinessExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessExtrasExt;

/**      
* 项目名称：dpqc-parent-manager-system   
* 类名称：OverdueController   
* 类描述：   逾期客户
* 创建人：zhangzj
* 创建时间：2017年4月24日 上午10:19:43   
* 修改人：zhangzj
* 修改时间：2017年4月24日 上午10:19:43   
* 修改备注：   
* @version V1.0     
*/ 
@RestController
@RequestMapping(value="DhOverdueController", produces="application/json;charset=UTF-8")
@Api(tags = {"逾期客户"}, produces="application/json;charset=UTF-8")
public class DhOverdueController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private IOverdueService overdueService=null;
	@Resource
	private IDhOverdueListService overdueListService=null;
	
	@Resource
	private IDhOverdueListHistoryService dhOverdueListHistoryService;
	@Resource
	private IOverdueBatchService overdueBatchService;
	
	@Resource
	private IDzLoanMiddleBankService dzLoanMiddleBankService;
	@Resource
	private FileProperty fileProperty;
	@Resource
    private ICachedDictionaryService cachedDictionaryService;
	@Resource
	private IYwBusinessService ywBusinessService;
	@Resource
	private IYwBusinessLoanService ywBusinessLoanService;
	@Resource
	private IYwBusinessExtrasService ywBusinessExtrasService;
	
	private int yipipei=0;
	private int weipipei=0;

	/** 
	* @author zhangzj
	* @Title: batchImportDueList 
	* 
	* @param @return    设定文件 
	* @return ApiResponse    返回类型 
	* @version V1.0
	* @throws 
	*/
	@ApiOperation(value = "逾期客户批量导入",response = DhOverdue.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value="batchImportDueList",method = RequestMethod.POST)
	public ApiResponse batchImportDueList(String uploadName,String bankCode){
		if(uploadName ==null || "".equals(uploadName)){
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
		AbstractSysUser currentUser = getCurrentUser();
		int now=(int)(System.currentTimeMillis() / 1000);
//		new Thread(new Runnable() {
//
//			@Override
//			public void run() {
				Date date = new Date();
				String uuid=UUIDFactory.getUUID();
				long s1=System.currentTimeMillis();
				URL xmlpath = this.getClass().getClassLoader().getResource("");
				String pathTo="";
		        try {
					pathTo=String.valueOf(xmlpath)+new String(fileProperty.getUploadPath().getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		        if(pathTo.contains("file:/")){
		        	pathTo=pathTo.substring(6,pathTo.length());
		        }
				List<List<String>> list=ExcelUtil.getExcelContent(pathTo+uploadName,23);
				DhOverdueList due=null;
				List<DhOverdueList> listDhOverdue=new ArrayList<DhOverdueList>();
				YwBusinessExt ywbusinessExt=null;
				List<List<String>> listError=new ArrayList<List<String>>();
				for(int i=1;i<list.size();i++){
					for(int j=list.size()-1;j>i;j--){ 
						if(list.get(j).get(2).equals(list.get(i).get(2))){
							listError.add(list.get(j));
						}
					}
				}
				List<String> dueInfoList=CollectionInitUtil.emptyList();
				YwBusinessLoan ywBusinessLoan= null;
				DzLoanMiddleBank dzLoanMiddleBank=null;
				String busiId="";
				String cardNo="";
				String idOperatorPhone=null;
				String phaseOverdue=null;
				for(int i=1;i<list.size();i++){
					dueInfoList=list.get(i);
					if(dueInfoList.size()<23) break;
//					if(!dueInfoList.containsAll(getTitleRow())|| !getTitleRow().containsAll(dueInfoList)) break;
					due= new DhOverdueList();
					
					ywbusinessExt= new YwBusinessExt();
					ywbusinessExt.setCustomerNo(dueInfoList.get(5));
					ywbusinessExt.setDpStatus(DpStatus.NORMAL.getCode());
					ywbusinessExt.setBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());
					List<YwBusiness> listLoanAfter=ywBusinessService.selectByExt(ywbusinessExt);
					if(listLoanAfter.size()>1){
						dueInfoList.add("该客户有多笔订单，不支持导入");
						listError.add(dueInfoList);
						continue;
					}
					
					if(listLoanAfter.isEmpty()){
						dueInfoList.add("该客户在系统中查不到订单");
						listError.add(dueInfoList);
					}else{
						busiId=listLoanAfter.get(0).getId();
						cardNo=dueInfoList.get(2);
						ywBusinessLoan= new YwBusinessLoan();
						ywBusinessLoan.setBusiId(busiId);
						ywBusinessLoan=ywBusinessLoanService.selectRefined(ywBusinessLoan);
						if(ywBusinessLoan==null){
							throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
						}
						if(Double.valueOf(dueInfoList.get(14))-ywBusinessLoan.getAmountMonthly()>0){
							YwBusinessExtrasExt ywBusinessExtrasExt= new YwBusinessExtrasExt();
							ywBusinessExtrasExt.setBusiId(busiId);
							ywBusinessExtrasExt.setTypeExtras("overdue");
							List<YwBusinessExtras> listYwBusinessExtrasExt=ywBusinessExtrasService.selectByExt(ywBusinessExtrasExt);
							if(listYwBusinessExtrasExt!=null && listYwBusinessExtrasExt.size()>0){
								for (YwBusinessExtras ywBusinessExtras : listYwBusinessExtrasExt) {
									idOperatorPhone=null;
									phaseOverdue=null;
									if(ywBusinessExtras.getCodeExtras().equals("id_operator_phone")){
										idOperatorPhone=ywBusinessExtras.getValueExtras();
									}else if(ywBusinessExtras.getCodeExtras().equals("phase_overdue")){
										phaseOverdue=ywBusinessExtras.getValueExtras();
									}
								}
							}
							
							due.setId(UUIDFactory.getUUID());
							due.setBusiId(busiId);
							due.setCusId(listLoanAfter.get(0).getCustomerId());
							due.setMarginDebt(Double.valueOf(dueInfoList.get(14))-ywBusinessLoan.getAmountMonthly());
							due.setLoanAmount(listLoanAfter.get(0).getSignLoanAmount());
							due.setBatchId(uuid);
							due.setBankCode(bankCode);
							due.setBatchDate(dueInfoList.get(0));
							due.setAreaCode(dueInfoList.get(1));
							due.setIdOperatorPhone(idOperatorPhone);
							due.setPhaseOverdue(phaseOverdue);
							dzLoanMiddleBank= new DzLoanMiddleBank();
							dzLoanMiddleBank.setBusiId(busiId);
							dzLoanMiddleBank=dzLoanMiddleBankService.selectRefined(dzLoanMiddleBank);
							//如果银行登记的卡号和EXCEL中的卡号不一样，修改贷中银行信息表中的卡号
							if(dzLoanMiddleBank !=null){
								if(!dzLoanMiddleBank.getCardnoRefund().equals(cardNo)){
									DzLoanMiddleBank dzLoanMiddleBank1= new DzLoanMiddleBank();
									dzLoanMiddleBank1.setId(dzLoanMiddleBank.getId());
									dzLoanMiddleBank1.setCardnoRefund(cardNo);
									dzLoanMiddleBank1.setRemarks("原先卡号:"+dzLoanMiddleBank.getCardnoRefund()+"，现在卡号:"+cardNo);
									dzLoanMiddleBankService.saveUpdateAndDelete(dzLoanMiddleBank1, OperateType.edit);
								}
							}
							
							due.setCardNo(cardNo);//逾期状态、逾期阶段excel没有
							due.setCusName(dueInfoList.get(3));
							due.setSexDisplay(dueInfoList.get(4));
							due.setCusIdno(dueInfoList.get(5));
							//分期金额
							due.setDevideAmount(Double.valueOf(dueInfoList.get(6)));
							due.setCurrency(String.valueOf(dueInfoList.get(7)));
							due.setFeeTotal(Double.valueOf(dueInfoList.get(8)));
							due.setLoanMonth((int)Double.parseDouble(dueInfoList.get(9)));
							due.setAmountAmortized(Double.valueOf(dueInfoList.get(10)));
							due.setAmountRemainder(Double.valueOf(dueInfoList.get(11)));
							try {
								due.setDateTrade(DateUtil.strToTimestamp(dueInfoList.get(12),"yyyy-MM-dd"));
							} catch (Exception e) {
								e.printStackTrace();
							}
							due.setBalanceCard(Double.valueOf(dueInfoList.get(13)));
							//昨日最优还款额
							due.setAmountMonthly(Double.valueOf(dueInfoList.get(14)));
							due.setOverdueCountContinuous((int)Double.parseDouble(dueInfoList.get(15)));
							due.setOverdueCountTotal((int)Double.parseDouble(dueInfoList.get(16)));
							due.setOverdueCountTotalReal((int)Double.parseDouble(dueInfoList.get(16)));
							due.setTelephone(dueInfoList.get(22));
							due.setDateOverdue(date);
							due.setDpStatus(1);
							due.setTypeData(1);
							due.setOverdueStatus(RefundStatus.YU_QI.getCode());
//							due.setPhaseOverdue("01");
							String ccol1="";
							Double d=(Double.parseDouble(dueInfoList.get(6))+(Double.parseDouble(dueInfoList.get(8)))/Double.parseDouble(dueInfoList.get(9)));
							if(d!=null){
								ccol1=d.toString();
							}
							if(d.toString().contains(".")){
								if(ccol1.length()- (ccol1.indexOf(".")+1) >=2){
									ccol1=ccol1.substring(0,ccol1.indexOf(".")+3);
								}
							}
							due.setDcol1(BigDecimal.valueOf(Double.parseDouble(ccol1)));
							due.setDcol2(BigDecimal.valueOf(Double.parseDouble(dueInfoList.get(14))-Double.parseDouble(ccol1)));
							due.setCreated(now);
							due.setCreator(currentUser.getId());
							due.setCreatorName(currentUser.getName());
							due.setModified(now);
							due.setModifier(currentUser.getId());
							due.setModifierName(currentUser.getName());
							due.setSalesmanCode(listLoanAfter.get(0).getSalesmanCode());
							listDhOverdue.add(due);
						}
						}
					}
				
//					ExcelUtil.importExcel(pathTo+"错误逾期客户.xlsx", ExcelTitleRowConsts.EXCELTYPE1, listError, getTitleRow());
				
					logger.debug("导入错误数据到EXCEL成功！");
					yipipei=listDhOverdue.size();
					weipipei=list.size()-yipipei-1;
					if(listDhOverdue!=null &&listDhOverdue.size()>0){
						//清空逾期客户表同一个银行的所有信息
						overdueService.deleteByBankCode(bankCode);
						
						overdueService.insertBatch(listDhOverdue);
						
						//清空逾期历史记录表
						Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
					    int day=aCalendar.getActualMaximum(Calendar.DATE);
					    int year=aCalendar.get(Calendar.YEAR);
					    int month = aCalendar.get(Calendar.MONTH) + 1;
					    int month1 = aCalendar.get(Calendar.MONTH);
					    String delDate="";
					    if(day>25){
					    	delDate=year+"-"+month+"-"+day;
					    }else{
					    	delDate=year+"-"+month1+"-"+day;
					    }
					    Map<String,Object> map=new HashMap<String,Object>();
					    map.put("bankCode", bankCode);
					    map.put("delDate", delDate);
				 		dhOverdueListHistoryService.deleteByBankCode(map);
						
						dhOverdueListHistoryService.insertBatch(listDhOverdue);
						
						//逾期批次表插入数据
						DhOverdueBatch overdueBatch=new DhOverdueBatch();
						overdueBatch.setId(uuid);
						overdueBatch.setDateReceipt(date);
						overdueBatch.setBank(bankCode);
						overdueBatch.setNumReceipt(listDhOverdue.size());
						overdueBatchService.insert(overdueBatch);
					}
					long s3=System.currentTimeMillis();
					logger.debug("导入逾期客户列表所需要的时间："+(s3-s1)/1000+"秒！");
					
					//业务状态是“已放款”并且还款状态是“逾期”的业务数据的还款状态更改为“曾经逾期”
					YwBusinessExt ywBusinessExt=new YwBusinessExt();
//					ywBusinessExt.setBusiStatusMore(BusiStatus.FENG_KONG_ZONG_JIAN_SHEN_HE_SHI_BAI.getCode());
//					ywBusinessExt.setBusiStatusLess(BusiStatus.HUAI_KUAN_ZHONG.getCode());
					
					ywBusinessExt.setBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());
					ywBusinessExt.setBankLoan(bankCode);
					ywBusinessExt.setRefundStatus(RefundStatus.YU_QI.getCode());
					ywBusinessService.updateRefundStatus(ywBusinessExt);
					
					YwBusiness yw= new YwBusiness();
					//导入数据后，将业务数据还款状态改为逾期
					for (DhOverdueList dhOverdue : listDhOverdue) {
						yw= new YwBusiness();
						yw.setId(dhOverdue.getBusiId());
						yw.setRefundStatus(RefundStatus.YU_QI.getCode());
						ywBusinessService.saveUpdateAndDelete(yw, OperateType.edit);
					}
					if(listError!=null && listError.size()>0){
						ExcelUtil.importExcel(pathTo+"错误逾期客户.xlsx", ExcelTitleRowConsts.EXCELTYPE1, listError, getTitleRow());
//						return ApiResponse.fail(111111,"部分客户导入未成功，具体原因请查询 "+pathTo+"银行错误信息.xlsx");
					}
//			}
//			
//		}).start();
			Map<String,Object> map = success();
			map.put("yipipei", yipipei);
			map.put("weipipei", weipipei);
			return ApiResponse.success(map);
		}
			/** 
			* @author zhangzj
			* @Title: getTitleRow 
			* @Description: 获取导入excel的列表头
			* @param @return    设定文件 
			* @return List<String>    返回类型 
			* @version V1.0
			* @throws 
			*/
			private List<String> getTitleRow() {
				List<String> arr1= new ArrayList<String>();
				arr1.add(ExcelTitleRowConsts.EXCELROW0);
				arr1.add(ExcelTitleRowConsts.EXCELROW1);
				arr1.add(ExcelTitleRowConsts.EXCELROW2);
				arr1.add(ExcelTitleRowConsts.EXCELROW3);
				arr1.add(ExcelTitleRowConsts.EXCELROW4);
				arr1.add(ExcelTitleRowConsts.EXCELROW5);
				arr1.add(ExcelTitleRowConsts.EXCELROW6);
				arr1.add(ExcelTitleRowConsts.EXCELROW7);
				arr1.add(ExcelTitleRowConsts.EXCELROW8);
				arr1.add(ExcelTitleRowConsts.EXCELROW9);
				arr1.add(ExcelTitleRowConsts.EXCELROW10);
				arr1.add(ExcelTitleRowConsts.EXCELROW11);
				arr1.add(ExcelTitleRowConsts.EXCELROW12);
				arr1.add(ExcelTitleRowConsts.EXCELROW13);
				arr1.add(ExcelTitleRowConsts.EXCELROW14);
				arr1.add(ExcelTitleRowConsts.EXCELROW15);
				arr1.add(ExcelTitleRowConsts.EXCELROW16);
				arr1.add(ExcelTitleRowConsts.EXCELROW17);
				arr1.add(ExcelTitleRowConsts.EXCELROW18);
				arr1.add(ExcelTitleRowConsts.EXCELROW19);
				arr1.add(ExcelTitleRowConsts.EXCELROW20);
				arr1.add(ExcelTitleRowConsts.EXCELROW21);
				arr1.add(ExcelTitleRowConsts.EXCELROW22);
				return arr1;
			}
	/** 
	* @author zhangzj
	* @Title: queryDueList 
	* @Description: 查询逾期客户列表
	* @param @param overdueListExt
	* @param @return    设定文件 
	* @return ApiResponse    返回类型 
	* @version V1.0
	* @throws 
	*/
	@ApiOperation(value = "查询逾期客户列表",response = DhOverdue.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value="queryDueList",method = RequestMethod.POST)
	public ApiResponse queryDueList(@ModelAttribute DhOverdueExt overdueListExt){
		overdueListExt.notDeleted();
		PageVo page = getPage(overdueListExt);
		int records =overdueService.countByExt(overdueListExt);
		page.setRecords(records);
		if (records > 0) {
            List<DhOverdueVo> overdueList = overdueService.selectByExt(overdueListExt);
            for(int i=0;i<overdueList.size();i++){
            	overdueList.get(i).setBankCodeDisplay(cachedDictionaryService.getName(overdueList.get(i).getBankCode(), DataDicType.LOAN_BANK));
            	overdueList.get(i).setIssue(i+1);
            }
            page.setRows(overdueList);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
		return ApiResponse.success(page);
	}
	/** 
	* @author zhangzj
	* @Title: previewDueList 
	* @Description: 预览excel列表
	* @param @param uploadName
	* @param @return    设定文件 
	* @return ApiResponse    返回类型 
	* @version V1.0
	* @throws 
	*/
	@ApiOperation(value = "预览excel列表",response = DhOverdue.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value="previewDueList",method = RequestMethod.POST)
	public ApiResponse previewDueList(String uploadName,boolean initFlag){
		if(initFlag==true){
			return ApiResponse.success(CollectionInitUtil.emptyList());
		}
		if(uploadName ==null || "".equals(uploadName)){
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
		URL xmlpath = this.getClass().getClassLoader().getResource("");
		String pathTo="";
        try {
			pathTo=String.valueOf(xmlpath)+new String(fileProperty.getUploadPath().getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        if(pathTo.contains("file:/")){
        	pathTo=pathTo.substring(6,pathTo.length());
        }
		
		
		List<List<String>> list=ExcelUtil.getExcelContent(pathTo+uploadName,23);
		if(list ==null || list.size()==0){
			return ApiResponse.fail(100300,"查询不到excel数据，请选择正确的excel数据导入！");
		}
		if(!list.get(0).containsAll(getTitleRow())|| !getTitleRow().containsAll(list.get(0))){
			return ApiResponse.fail(100300,"查询不到excel数据，请选择正确的excel数据导入！");
		};
		DhOverdue due=null;
		List<DhOverdue> listDhOverdue=new ArrayList<DhOverdue>();
		for(int i=1;i<list.size();i++){
			List<String> dueInfoList=list.get(i);
			if(dueInfoList==null || dueInfoList.size()<23){
				break;
			}
			due= new DhOverdue();
			due.setOverdueCountContinuous((int)Double.parseDouble(dueInfoList.get(15)));
			due.setOverdueCountTotal((int)Double.parseDouble(dueInfoList.get(16)));
			due.setAmountMonthly(Double.valueOf(dueInfoList.get(14)));
			due.setCusName(dueInfoList.get(3));
			due.setLoanAmount(Double.valueOf(dueInfoList.get(6)));
			due.setCusIdno(dueInfoList.get(5));
			due.setLoanMonth((int)Double.parseDouble(dueInfoList.get(9)));
			due.setAmountAmortized(Double.valueOf(dueInfoList.get(10)));
			due.setAmountRemainder(Double.valueOf(dueInfoList.get(11)));
			due.setDateOverdue(DateUtil.convertStr2Date(dueInfoList.get(12)));
			listDhOverdue.add(due);
			if(i>=50) break;
		}
		if(listDhOverdue ==null || listDhOverdue.size()==0){
			return ApiResponse.fail(100300,"查询不到excel数据，请选择正确的excel数据导入！");
		}
		PageVo page = new PageVo();
		page.setRecords(1);
		page.setRows(listDhOverdue);
		return ApiResponse.success(page);
	}
	
}
